<template>
  <view>
    <div class="box">
      <div class="row">
        <div class="col">
          <div class="label">开关</div>
          <t-radio-group v-model="form.luckyStatus" default-value="1">
            <t-radio value="1">开</t-radio>
            <t-radio value="0">关</t-radio>
          </t-radio-group>
        </div>
      </div>
      <div class="row">
        <div class="col">
          <div class="label">名称</div>
          <t-input v-model="form.luckyTitle" placeholder="请输入内容" />
        </div>
      </div>
      <div class="row">
        <div class="col">
          <div class="label">积分消耗</div>
          <t-input-number v-model="form.costs" />
          <div class="tag">转一次转盘所需的转盘币</div>
        </div>
      </div>
      <div class="row">
        <div class="col">
          <div class="label" style="color: black; font-size: 14px; font-weight: 600">邀请奖励设置</div>
        </div>
      </div>
      <!-- 邀请奖励设置 -->
      <div>
        <div class="invite" v-for="(item, index) in form.invitationList">
          <div class="row">
            <div class="col">
              <div class="label">被邀请等级</div>
              <t-select v-model="item.vipLevel">
                <t-option
                  v-for="i in gradeList"
                  :key="i.grade"
                  :label="i.name"
                  :value="i.grade"
                  :disabled="selectedVipLevels.includes(i.grade) && item.vipLevel !== i.grade"
                />
              </t-select>
            </div>
          </div>
          <div class="row">
            <div class="col">
              <div class="label">奖励邀请人</div>
              <t-input-number v-model="item.inviter" />
            </div>
          </div>
          <div class="row">
            <div class="col">
              <div class="label">奖励被邀请人</div>
              <t-input-number v-model="item.invited" />
              <div class="tag">邀请1个用户成为该等级会员后奖励多少转盘币，0为不奖励</div>
            </div>
          </div>
          <t-link theme="danger" style="font-weight: 600; margin-left: 37px" @click="deleteClickOp(index)">删除</t-link>
        </div>
        <t-button theme="primary" style="transform: translateX(120px)" @click="addInvite">
          <template #icon><add-icon /></template>
          添加
        </t-button>
      </div>
      <div class="row">
        <div class="col">
          <div class="label" style="margin-right: 10px">图标</div>
          <UpLoad v-model:image="form.luckyIcon" :key="form.luckyIcon"></UpLoad>
        </div>
      </div>
      <div class="row">
        <div class="col" style="align-items: start; flex-wrap: nowrap">
          <div class="label" style="margin-right: 10px">说明</div>
          <TinymceEditor v-model="form.luckyDesc" ref="editor"></TinymceEditor>
        </div>
      </div>
      <div class="btnBox">
        <t-button theme="primary" size="large" @click="onSubmit">立即提交</t-button>
        <t-button variant="outline" theme="default" size="large" @click="unGetSetting">重置</t-button>
      </div>
    </div>
  </view>
</template>
<script setup lang="ts">
import TinymceEditor from '@/components/tinymceEditor/index.vue';
import UpLoad from '@/components/upLoad/index.vue';
import { getSetting, addSetting, updateSetting } from '@/api/system/basicSetting/4';
import { MessagePlugin } from 'tdesign-vue-next';
import { ref, computed } from 'vue';
import { getGradeList } from '@/api/member/level';

interface invitation {
  vipLevel: string | number | null;
  inviter: string | number | null;
  invited: string | number | null;
}

interface FormDataType {
  id: string | number | null;
  luckyStatus: string;
  luckyTitle: string;
  costs: string | number | null;
  invitationList: Array<invitation>;
  luckyGiftTimes: number | string;
  luckyIcon: string | null; // 根据 UpLoad 组件的值类型调整，可能是 URL 或 File 对象
  luckyDesc: string;
}
const INITIAL_DATA: FormDataType = {
  id: null,
  luckyStatus: '1',
  luckyTitle: '',
  costs: null,
  invitationList: [
    {
      vipLevel: null,
      inviter: null,
      invited: null,
    },
  ],
  luckyGiftTimes: 0,
  luckyIcon: null,
  luckyDesc: '',
};
const form = ref({ ...INITIAL_DATA });

// 添加邀请奖励设置
const addInvite = () => {
  form.value.invitationList.push({
    vipLevel: undefined,
    inviter: undefined,
    invited: undefined,
  });
};

// 删除邀请奖励设置
const deleteClickOp = (index: number) => {
  form.value.invitationList.splice(index, 1);
};

const selectedVipLevels = computed(() => {
  return form.value.invitationList
    .map((item) => item.vipLevel)
    .filter((value) => value !== null && value !== undefined && value !== '');
});

// 等级列表
import { useGradeStore } from '@/store/modules/member';
const gradeStore = useGradeStore();
const gradeList = ref<any[]>([]);
gradeList.value = gradeStore.gradeList;

const emit = defineEmits(['handleClickDelete']);

const onSubmit = () => {
  emit('handleClickDelete');
};
const submit = async () => {
  // 校验 invitationList 是否合法
  if (!validateInvitationList(form.value.invitationList)) {
    MessagePlugin.warning('邀请奖励设置中存在空值，请检查后重新提交');
    return;
  }
  try {
    const res = form.value?.id ? await updateSetting(form.value) : await addSetting(form.value);
    if (res.code == 200) {
      MessagePlugin.success('提交成功');
      unGetSetting();
    }
  } catch (error) {
    console.log(error);
  }
};

function validateInvitationList(invitationList) {
  if (!Array.isArray(invitationList)) {
    console.warn('invitationList 不是一个数组');
    return false;
  }

  for (let i = 0; i < invitationList.length; i++) {
    const item = invitationList[i];

    // 检查是否是对象
    if (typeof item !== 'object' || item === null) {
      console.warn(`第 ${i + 1} 项不是一个有效对象`);
      return false;
    }

    // 检查每个字段
    if (
      item.vipLevel == null || // 拦截 null 和 undefined
      (typeof item.vipLevel === 'string' && item.vipLevel.trim() === '') || // 如果是字符串，则不允许空
      item.inviter == null ||
      (typeof item.inviter === 'string' && item.inviter.trim() === '') ||
      item.invited == null ||
      (typeof item.invited === 'string' && item.invited.trim() === '')
    ) {
      console.warn(`第 ${i + 1} 项存在空值或 null，请检查输入内容`);
      return false;
    }
  }

  return true;
}

// 获取配置
const unGetSetting = async () => {
  try {
    const res = await getSetting();
    form.value = res.data ? res.data : { ...INITIAL_DATA };
    if (!res.data.invitationList) {
      form.value.invitationList = [];
      addInvite();
    }
  } catch (error) {
    console.log(error);
  }
};

unGetSetting();

defineExpose({
  submit,
});
</script>
<style lang="less" scoped>
.box {
  padding: 10px;
  .invite {
    display: flex;
    align-items: center;
  }

  .row {
    display: flex;
    padding: 25px 0;

    &:nth-child(2n) {
      // background-color: #f2f2f2;
    }

    .col {
      flex: 1;
      display: flex;
      align-items: center;
      flex-wrap: wrap;

      .label {
        width: 110px;
        font-size: 12px;
        text-align: right;
        word-wrap: break-word;
        word-break: break-word;
        color: #666;
      }

      .tag {
        min-width: 110px;
        font-size: 12px;
        color: #999;
      }
    }
  }

  .btnBox {
    display: flex;
    justify-content: center;
  }
}
</style>

<style class="less">
.col {
  .t-input__wrap {
    width: 240px;
    margin: 0 10px;

    & .t-input {
      height: 38px;
      font-size: 12px;
    }
  }

  .t-select__wrap {
    width: 240px;

    .t-select-input {
      width: 240px;
      height: 38px;
      font-size: 12px;
    }
  }

  .t-radio-group {
    margin: 0 10px;
  }

  .t-textarea {
    width: 400px;
    margin: 0 10px;

    .t-textarea__inner {
      width: 400px;
      font-size: 12px;
    }
  }

  .t-input-number.t-input-number--row {
    width: 240px;
    display: flex;
    align-items: center;
    padding: 0 38px;
    margin: 0 10px;

    .t-button.t-button--variant-outline.t-button--theme-default.t-button--shape-square.t-button--icon-only {
      width: 38px;
      height: 38px;
    }

    .t-input__wrap {
      min-width: 156px;
    }
  }
}
</style>
